<?php

namespace App\Kuafu\Order\Model;

use App\Kuafu\Base\Model\BaseModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class SeparateTimeLogModel extends BaseModel
{
    protected $connection = 'mysqlDataStatistics';
    protected $table      = 'separate_time_logs';

    protected $fillable = ['id', 'startTime', 'endTime', 'type', 'createdAt', 'path'];

    protected $hidden = [];

    public $timestamps = false;

    const TYPE_MYSQL = 0;
    const TYPE_CLICKHOUSE = 1;

    public static function add(int $startTime, int $endTime, int $type)
    {
        try {
            // api/command中+时间限制1分钟
            if (app()->runningInConsole()) {
                $cacheKey = implode(' ', $_SERVER['argv'] ?? []);
            } else {
                $cacheKey = request()->path();
            }
        } catch (\Exception $e) {
            $cacheKey = '';
            Log::warning($e);
        }

        if (Cache::store('array')->has($cacheKey)) {
            return;
        }

        self::query()->insert([
            'startTime' => date('Y-m-d H:i:s', $startTime),
            'endTime'   => date('Y-m-d H:i:s', $endTime),
            'type'      => $type,
            'createdAt' => time(),
            'path'      => $cacheKey,
        ]);

        Cache::store('array')->set($cacheKey, 1, 60);
    }
}
